<template>
	<view class="decoration-container">
		<view class="status-tabs">
			<view 
				v-for="(item, index) in statusTabs" 
				:key="index" 
				class="tab-item" 
				:class="{ active: currentTab === index }"
				@click="switchTab(index)"
			>
				{{ item.name }}
			</view>
		</view>
		
		<view class="application-list">
			<view v-if="loading" class="loading">
				<uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
			</view>
			
			<view v-else-if="applicationList.length === 0" class="empty-list">
				<image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
				<view class="empty-text">暂无装修备案记录</view>
			</view>
			
			<view v-else>
				<view 
					v-for="(item, index) in applicationList" 
					:key="index" 
					class="application-item card"
					@click="goToDetail(item.application_id)"
				>
					<view class="item-header">
						<view class="title">装修备案申请</view>
						<view class="status" :class="getStatusClass(item.status)">{{ item.status }}</view>
					</view>
					
					<view class="item-info">
						<view class="info-row">
							<text class="label">申请单元:</text>
							<text class="value">{{ item.unit_info }}</text>
						</view>
						<view class="info-row">
							<text class="label">施工单位:</text>
							<text class="value">{{ item.construction_company }}</text>
						</view>
						<view class="info-row">
							<text class="label">预计工期:</text>
							<text class="value">{{ item.estimated_duration }} 天</text>
						</view>
						<view class="info-row">
							<text class="label">申请日期:</text>
							<text class="value">{{ item.application_date }}</text>
						</view>
						<view class="info-row" v-if="item.approval_opinion">
							<text class="label">审批意见:</text>
							<text class="value opinion">{{ item.approval_opinion }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<view class="fixed-bottom">
			<button class="submit-btn" @click="goToApply">申请装修备案</button>
		</view>
	</view>
</template>

<script>
	import { getCurrentUserDecorationApplications } from '@/api/services.js'
	import eventBus from '@/utils/eventBus.js'
	
	export default {
		data() {
			return {
				statusTabs: [
					{ name: '全部', status: '' },
					{ name: '待审核', status: ['待审核', '审核中'] },
					{ name: '已审核', status: ['审核通过', '审核驳回'] },
					{ name: '施工中', status: '施工中' },
					{ name: '已完成', status: ['已完工', '已验收'] }
				],
				currentTab: 0,
				applicationList: [],
				loading: false,
				loadingText: {
					contentdown: '正在加载...',
					contentrefresh: '正在加载...',
					contentnomore: '没有更多数据了'
				},
				eventBusRegistered: false // 添加标记，避免多次注册事件
			}
		},
		onLoad(options) {
			this.registerEventBus()
			
			// 检查是否有refresh参数
			if (options && options.refresh === 'true') {
				console.log('检测到refresh参数，正在刷新列表')
			}
			this.getApplicationList()
		},
		onShow() {
			// 页面显示时也注册事件，确保从其他页面返回时能接收通知
			this.registerEventBus()
			// 页面每次显示时刷新列表
			this.getApplicationList()
		},
		onHide() {
			// 页面隐藏时解除事件绑定
			this.unregisterEventBus()
		},
		onUnload() {
			// 页面卸载时解除事件绑定
			this.unregisterEventBus()
		},
		methods: {
			// 注册事件总线
			registerEventBus() {
				if (!this.eventBusRegistered) {
					eventBus.on('refreshDecorationList', () => {
						console.log('收到刷新装修备案列表事件')
						this.getApplicationList()
					})
					this.eventBusRegistered = true
				}
			},
			
			// 解除事件总线
			unregisterEventBus() {
				eventBus.off('refreshDecorationList')
				this.eventBusRegistered = false
			},
			
			// 切换状态标签
			switchTab(index) {
				this.currentTab = index
				this.getApplicationList()
			},
			
			// 获取装修备案列表
			async getApplicationList() {
				console.log('正在加载装修备案列表...')
				this.loading = true
				try {
					const params = {}
					const currentStatus = this.statusTabs[this.currentTab].status
					
					if (currentStatus) {
						if (Array.isArray(currentStatus)) {
							// 如果是数组，需要在后端处理多状态查询
							params.status = currentStatus.join(',')
						} else {
							params.status = currentStatus
						}
					}
					
					try {
						// 使用API获取当前用户的装修备案列表
						const res = await getCurrentUserDecorationApplications(params)
						console.log('装修备案列表获取成功:', JSON.stringify(res, null, 2))
						
						this.applicationList = res
						
						// 如果列表为空，显示提示
						if (!res || res.length === 0) {
							uni.showToast({
								title: '暂无装修备案记录',
								icon: 'none'
							})
						}
					} catch (apiError) {
						console.error('API请求错误:', apiError)
						
						// 显示具体的错误信息
						let errorMsg = '获取数据失败'
						if (apiError.message) {
							errorMsg += ': ' + apiError.message
						}
						
						uni.showToast({
							title: errorMsg,
							icon: 'none',
							duration: 3000
						})
						
						this.applicationList = []
					}
				} catch (error) {
					console.error('获取装修备案列表失败', error)
					
					uni.showToast({
						title: '获取数据时发生错误',
						icon: 'none',
						duration: 2000
					})
					
					this.applicationList = []
				} finally {
					this.loading = false
				}
			},
			
			// 获取状态对应的样式类
			getStatusClass(status) {
				switch (status) {
					case '待审核':
					case '审核中':
						return 'status-pending'
					case '审核通过':
					case '施工中':
						return 'status-processing'
					case '已完工':
					case '已验收':
						return 'status-completed'
					case '审核驳回':
						return 'status-rejected'
					default:
						return ''
				}
			},
			
			// 跳转到详情页
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/services/decoration/detail?id=${id}`
				})
			},
			
			// 跳转到申请页
			goToApply() {
				uni.navigateTo({
					url: '/pages/services/decoration/apply?from_list=true'
				})
			}
		}
	}
</script>

<style lang="scss">
	.decoration-container {
		padding: 20rpx;
		padding-bottom: 120rpx;
		background-color: #F8F8F8;
		min-height: 100vh;
		
		.status-tabs {
			display: flex;
			background-color: #FFFFFF;
			border-radius: 12rpx;
			margin-bottom: 20rpx;
			overflow: hidden;
			box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
			
			.tab-item {
				flex: 1;
				text-align: center;
				padding: 20rpx 0;
				font-size: 28rpx;
				color: #666;
				position: relative;
				
				&.active {
					color: #2979ff;
					font-weight: bold;
					
					&:after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 40rpx;
						height: 6rpx;
						background-color: #2979ff;
						border-radius: 3rpx;
					}
				}
			}
		}
		
		.application-list {
			.loading, .empty-list {
				padding: 60rpx 0;
				text-align: center;
			}
			
			.empty-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 20rpx;
			}
			
			.empty-text {
				color: #999;
				font-size: 28rpx;
			}
			
			.application-item {
				margin-bottom: 20rpx;
				
				.item-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;
					
					.title {
						font-size: 32rpx;
						font-weight: bold;
					}
					
					.status {
						font-size: 24rpx;
						padding: 4rpx 16rpx;
						border-radius: 20rpx;
						
						&.status-pending {
							color: #ff9900;
							background-color: rgba(255, 153, 0, 0.1);
						}
						
						&.status-processing {
							color: #2979ff;
							background-color: rgba(41, 121, 255, 0.1);
						}
						
						&.status-completed {
							color: #19be6b;
							background-color: rgba(25, 190, 107, 0.1);
						}
						
						&.status-rejected {
							color: #dd524d;
							background-color: rgba(221, 82, 77, 0.1);
						}
					}
				}
				
				.item-info {
					background-color: #f9f9f9;
					border-radius: 8rpx;
					padding: 20rpx;
					
					.info-row {
						display: flex;
						margin-bottom: 10rpx;
						
						&:last-child {
							margin-bottom: 0;
						}
						
						.label {
							width: 150rpx;
							color: #666;
							font-size: 26rpx;
						}
						
						.value {
							flex: 1;
							font-size: 26rpx;
							
							&.opinion {
								color: #ff9900;
							}
						}
					}
				}
			}
		}
		
		.fixed-bottom {
			position: fixed;
			bottom: 30rpx;
			left: 30rpx;
			right: 30rpx;
			
			.submit-btn {
				background-color: #2979ff;
				color: #fff;
				border-radius: 45rpx;
				font-size: 32rpx;
				height: 80rpx;
				line-height: 80rpx;
			}
		}
	}
</style> 